package com.hzdp.handles.rival.pipelines;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hzdp.constant.CommonConstants;
import com.hzdp.dao.RivalProductDao;
import com.hzdp.dao.po.RivalProductPO;
import com.hzdp.spring.BeanFactory;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.log4j.Logger;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 把抓取的数据根据指定格式存入db
 * <p/>
 * Created by leo on 15/11/28.
 */
public class DBPipeline implements Pipeline {

    private final Logger logger = Logger.getLogger(this.getClass());

    private static RivalProductDao rivalProductDao = (RivalProductDao)BeanFactory.getInstance().getBean("rivalProductDao");

    private int sourceCompanyId;
    private String category;
    public DBPipeline(int sourceCompanyId, String category) {
        this.sourceCompanyId = sourceCompanyId;
        this.category = category;
    }


    @Override
    public void process(ResultItems resultItems, Task task) {
        if(MapUtils.isEmpty(resultItems.getAll())){
            return;
        }
        RivalProductPO rivalProductPO = new RivalProductPO();
        rivalProductPO.setCompanyId(sourceCompanyId);
        rivalProductPO.setCompanyCategory(category);
        rivalProductPO.setName((String)resultItems.get(CommonConstants.NAME));
        rivalProductPO.setSourceUrl((String)resultItems.get(CommonConstants.SOUCRCE_URL));
        List<String> urlList = (List<String>) resultItems.get(CommonConstants.IMG_URLS);

        rivalProductPO.setImgUrls(StringUtils.join(urlList,","));
        Map<String, String> descMap = (Map<String, String>) resultItems.get(CommonConstants.DESCS);
        try {
            rivalProductPO.setDescs( new ObjectMapper().writeValueAsString(descMap));
        } catch (JsonProcessingException e) {
            logger.error(e);
        }
        rivalProductPO.setBrandName((String)resultItems.get(CommonConstants.BRAND_NAME));

        try {
            rivalProductDao.insert(rivalProductPO);
        } catch (SQLException e) {
            logger.error(e);
        }
    }

    public int getSourceCompanyId() {
        return sourceCompanyId;
    }

    public void setSourceCompanyId(int sourceCompanyId) {
        this.sourceCompanyId = sourceCompanyId;
    }
}
